package com.tjsinfo.tjsoa.baobiao.action;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONObject;

import sun.misc.Compare;

import com.tjsinfo.tjsoa.baobiao.bo.IHqBBSetManage;
import com.tjsinfo.tjsoa.baobiao.bo.IHqBBYhManage;
import com.tjsinfo.tjsoa.baobiao.bo.IHqGjjManage;
import com.tjsinfo.tjsoa.baobiao.vo.THqBBYh;
import com.tjsinfo.tjsoa.baobiao.vo.THqZfgjjybb;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.system.vo.User; 

public class GjjManageAction extends DispatchAction {
	
	private IHqBBYhManage hqBBYhManage;
    private IHqGjjManage hqGjjManage;
    private IHqBBSetManage hqBBSetManage;

	public IHqBBYhManage getHqBBYhManage() {
		return hqBBYhManage;
	}

	public void setHqBBYhManage(IHqBBYhManage hqBBYhManage) {
		this.hqBBYhManage = hqBBYhManage;
	}
	
	public IHqGjjManage getHqGjjManage() {
		return hqGjjManage;
	}

	public void setHqGjjManage(IHqGjjManage hqGjjManage) {
		this.hqGjjManage = hqGjjManage;
	}

	public IHqBBSetManage getHqBBSetManage() {
		return hqBBSetManage;
	}

	public void setHqBBSetManage(IHqBBSetManage hqBBSetManage) {
		this.hqBBSetManage = hqBBSetManage;
	}
		/**
		 * 准备进入上报统计表界面
		 * @param mapping
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws Exception
		 */
	public ActionForward getTjb(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)throws Exception {
				
			String yueString = request.getParameter("yue");
		    if ("".equals(yueString)|| yueString==null){
		    	yueString =getLastMonth();
		    }
		    		    			    
	    	User sessionUser = ToolKit.getSessionUser(request);
	    	String usernameString = "";
	    	if (null==sessionUser){
	    		usernameString = request.getParameter("user");
	    		if ("".equals(usernameString)|| null==usernameString){
	    			return mapping.findForward("failed");
	    		}else{
		    		usernameString = URLDecoder.decode(usernameString,"utf-8");
		    		User tempUser = new User();
	    			tempUser.setUsername(usernameString);
	    			request.getSession().setAttribute("user", tempUser);
	    		}
	    	}else{
	    		usernameString = sessionUser.getUsername();
	    	}
	    	List<THqBBYh> BBYhList = hqBBYhManage.findbyUser(usernameString,2);

	    	if (BBYhList.size()<1){    //当前用户不在报表用户名单中
	    		return mapping.findForward("failed");
	    	}
	    	Integer	yhidInteger = BBYhList.get(0).getId();
	    
	        List<THqZfgjjybb> tjbList = hqGjjManage.findByYueYh(yueString , yhidInteger);
	        String typeString ="";
		    if (tjbList.size()<1){
		    	THqZfgjjybb tjbtemp = new THqZfgjjybb(yhidInteger,BBYhList.get(0).getDwmch(),yueString,BBYhList.get(0).getRyxm());
		    	typeString ="add";
		        request.setAttribute("gjjtjb", tjbtemp);
		        request.setAttribute("riqi", ToolKit.FormatDate(new Date()));
		    }else{
		        request.setAttribute("gjjtjb", tjbList.get(0));
		        if ("0".equals(tjbList.get(0).getState())){
		        	request.setAttribute("riqi", ToolKit.FormatDate(new Date()));
		        }else{
		        	request.setAttribute("riqi", tjbList.get(0).getRq());
		    	}	
		    }
		    request.setAttribute("type", typeString);
			return mapping.findForward("getTjb");
		    
		}		
		/**
			 * 保存或提交统计表
			 * @param mapping
			 * @param form
			 * @param request
			 * @param response
			 * @return
			 * @throws Exception
			 */
	public ActionForward saveTjb(ActionMapping mapping, ActionForm form,
						HttpServletRequest request, HttpServletResponse response)throws Exception {
			THqZfgjjybb gjjybb=new THqZfgjjybb();
			gjjybb.setYhid(Integer.valueOf(request.getParameter("yhid")));
			gjjybb.setDwmch(request.getParameter("dwmch"));
			gjjybb.setZcrsh(Integer.valueOf(request.getParameter("zcrsh")));
			gjjybb.setByfcrsh(Integer.valueOf(request.getParameter("byfcrsh")));
			gjjybb.setLjfcrsh(Integer.valueOf(request.getParameter("ljfcrsh")));
			gjjybb.setTxzhq_rsh(Integer.valueOf(request.getParameter("txzhq_rsh")));
			gjjybb.setTxzhq_je(Double.valueOf(request.getParameter("txzhq_je")));
			gjjybb.setGfzhq_rsh(Integer.valueOf(request.getParameter("gfzhq_rsh")));
			gjjybb.setGfzhq_je(Double.valueOf(request.getParameter("gfzhq_je")));
			gjjybb.setHdzhq_rsh(Integer.valueOf(request.getParameter("hdzhq_rsh")));
			gjjybb.setHdzhq_je(Double.valueOf(request.getParameter("hdzhq_je")));
			gjjybb.setQtzhq_rsh(Integer.valueOf(request.getParameter("qtzhq_rsh")));
			gjjybb.setQtzhq_je(Double.valueOf(request.getParameter("qtzhq_je")));
			gjjybb.setByxkhrsh(Integer.valueOf(request.getParameter("byxkhrsh")));
			gjjybb.setYje(Double.valueOf(request.getParameter("yje")));			
			gjjybb.setBydrrsh(Integer.valueOf(request.getParameter("bydrrsh")));
			gjjybb.setByzhrje(Double.valueOf(request.getParameter("byzhrje")));
			gjjybb.setBydchrsh(Integer.valueOf(request.getParameter("bydchrsh")));
			gjjybb.setByzhchje(Double.valueOf(request.getParameter("byzhchje")));
			gjjybb.setByhjrsh(Integer.valueOf(request.getParameter("byhjrsh")));
			gjjybb.setYhjje(Double.valueOf(request.getParameter("yhjje")));
			gjjybb.setGjjjcye(Double.valueOf(request.getParameter("gjjjcye")));			
			gjjybb.setBeizhu(request.getParameter("beizhu"));
			gjjybb.setFzr(request.getParameter("fzr"));
			gjjybb.setCzy(request.getParameter("czy"));
			
			String yueString = request.getParameter("yue");
			String rqString = request.getParameter("riqi");
			String stateString = request.getParameter("state");
			
			gjjybb.setYue(yueString);
			gjjybb.setRq(rqString);
			gjjybb.setState(stateString);
			gjjybb.setIntime("0");
			
			if ("1".equals(stateString)){
				if(isIntime(rqString,yueString)){
					gjjybb.setIntime("1");
				}
			}
			String savetype = request.getParameter("type");
			if("add".equals(savetype)){
				hqGjjManage.addBaobiao(gjjybb);
			}else {
				gjjybb.setId(Integer.valueOf(request.getParameter("id")));
				hqGjjManage.updateBaobiao(gjjybb);
			}
			request.setAttribute("linkurl", "tjsinfo/tjsoa/baobiao/GjjManage.do?method=getTjb");
			request.setAttribute("message", "system.save.message");
			return mapping.findForward("success");
	}

	
	private boolean isIntime(String rqString, String yueString) {
			// TODO Auto-generated method stub
        Date riqiDate = ToolKit.FormatDate(rqString);
        
        String deadlineString = hqBBSetManage.getDeadline("2");
        if (deadlineString.length()==1){
        	deadlineString = "0"+deadlineString;
        }
        deadlineString = yueString.trim()+"-"+deadlineString;
               
		Calendar cal = Calendar.getInstance();
		cal.setTime(ToolKit.FormatDate(deadlineString));
	    cal.add(Calendar.MONTH, 1);
	    Date deadlineDate = cal.getTime();
		return (riqiDate.getTime()<deadlineDate.getTime());
	}

	/**
	 * 准备显示上报情况统计 
	 * @param mapping
	 * @param form
	 * @param requejst
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward toGetTjList(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)throws Exception {
		
	    String yueString = request.getParameter("yue");
	    if ("".equals(yueString)|| yueString==null){
	    	yueString =getLastMonth();
	    }
		request.setAttribute("yue", yueString);
		return mapping.findForward("GetTJList");		
	}
				
	/**
	 * 显示上报情况统计 
	 * @param mapping
	 * @param form
	 * @param requejst
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getTjList(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)throws Exception {
				
		String yueString = request.getParameter("yue");
	    	if ("".equals(yueString)|| yueString==null){
		    	yueString =getLastMonth();
		    }
	    List<THqZfgjjybb> tjbList = hqGjjManage.findByYue(yueString);
		Map<String,String> map = new HashMap();
		JSONArray array	 = new JSONArray();
		for(THqZfgjjybb tjbtemp:tjbList){
			map.put(String.valueOf(tjbtemp.getYhid()),String.valueOf(tjbtemp.getId()));
		}
		List<THqBBYh> yhList = hqBBYhManage.findAllenable(2);
		for(THqBBYh yhtemp:yhList){
			Object objtemp = map.get(String.valueOf(yhtemp.getId()));
			JSONObject obj = new JSONObject();
			obj.put("dwmch", yhtemp.getDwmch());
			obj.put("yue", yueString);
			if (objtemp==null){
				obj.put("exist", "0");
			}else{
				obj.put("exist", "1");
				obj.put("id",objtemp.toString());
			}
			array.put(obj);
		}
	 	response.getWriter().print(array);
		return null;
	}

	
	/**
	 * 显示某单位上报的报表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward viewshangbao(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		String idString = request.getParameter("id");
	    THqZfgjjybb gjjybb = hqGjjManage.findById(Integer.valueOf(idString));
	    List <THqZfgjjybb> gjjlastmonth = hqGjjManage.findByYueYh(getMonthBefore(gjjybb.getYue()), gjjybb.getYhid(), "1");
	    if (gjjlastmonth.size()>0){
	    	double jcyeDouble = gjjlastmonth.get(0).getGjjjcye()+gjjybb.getYhjje()+gjjybb.getByzhrje()-gjjybb.getByzhchje()
	    						-(gjjybb.getTxzhq_je()+gjjybb.getGfzhq_je()+gjjybb.getHdzhq_je()+gjjybb.getQtzhq_je());
	    	request.setAttribute("jcye", String.valueOf(jcyeDouble));
	    }
	    request.setAttribute("gjjybb", gjjybb);
	    request.setAttribute("type", "single");
	    request.setAttribute("riqi", gjjybb.getRq());
		return mapping.findForward("viewshangbao");
		}	

	/**
	 * 退回统计表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward sendBackTjb(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception {
		
	    Integer tjbid=Integer.valueOf(request.getParameter("id"));
		THqZfgjjybb tjbtemp = hqGjjManage.findById(tjbid);
		tjbtemp.setState("0");
		hqGjjManage.updateBaobiao(tjbtemp);
		request.setAttribute("linkurl", "tjsinfo/tjsoa/baobiao/GjjManage.do?method=toGetTjList");
		request.setAttribute("message", "system.save.message");
		return mapping.findForward("success");
		}	
	/**
	 * 汇总统计表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward collectTjb(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception {
		
	    String yueString = request.getParameter("yue");
		THqZfgjjybb tjbtemp = hqGjjManage.collectByYue(yueString);
	    request.setAttribute("gjjybb", tjbtemp);
	    request.setAttribute("type", "collect");
		request.setAttribute("riqi", "");
		return mapping.findForward("viewshangbao");
		}	

	/**
	 * 统计及时率
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward count(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception {
		
	    String yearString = request.getParameter("year");
	    String beginmonth = request.getParameter("beginmonth");
	    String endmonth = request.getParameter("endmonth");
	    Integer sumInteger = 0;
	    List<Map<String, String>> tempList = new ArrayList<Map<String,String>>();
	    if (yearString==null){
	    	if (beginmonth.compareTo(endmonth)>0){
	    		String tString=beginmonth;
	    		beginmonth=endmonth;
	    		endmonth=tString;
	    	}
	    	tempList = hqGjjManage.countIntime(beginmonth,endmonth);
	    	sumInteger = sumbymonth(beginmonth, endmonth);
	    }else{
	    	tempList = hqGjjManage.countIntime(yearString);
	    	sumInteger = sumbyyear(yearString);
	    }
	    
	    Map<String,String> jslMap = new HashMap();
	    for (Map<String, String> tempMap: tempList){
 	    	Float jsl=(Float.valueOf(tempMap.get("intimecount"))/sumInteger)*100;
	    	String jslString = String.valueOf((float)(Math.round(jsl*100))/100)+"%";  // 截取两位小数
	    	jslMap.put(tempMap.get("yhid"), jslString);
	    }
	    
	    List<THqBBYh> userList = hqBBYhManage.findAllenable(2);
  
		JSONArray array	 = new JSONArray();
			for (THqBBYh user : userList){
				Object objtemp = jslMap.get(String.valueOf(user.getId()));
	 			JSONObject jsObject = new JSONObject();
	 			jsObject.put("dwmch", user.getDwmch());
	 			if (objtemp==null){
	 				jsObject.put("jsl", "0.0%");
	 			}else{
	 				jsObject.put("jsl", objtemp);
	 			}
	 			array.put(jsObject);
		}
	 	response.getWriter().print(array);
		return null;
		}		

	/**
	 * 计算当前月前一个月的月份
	 */
	public String getLastMonth(){
		
		Calendar cal = Calendar.getInstance();
	    cal.add(Calendar.MONTH, -1);
 	   	String yueString = ToolKit.FormatDate(cal.getTime()).substring(0,7);
 	    return yueString;
	}
	
	/**
	 * 计算上个月的月份
	 */
	public String getMonthBefore(String month){
		
		Date datetemp = ToolKit.FormatDate(month +"-01");
		Calendar cal = Calendar.getInstance();
		cal.setTime(datetemp);
	    cal.add(Calendar.MONTH, -1);
 	   	String yueString = ToolKit.FormatDate(cal.getTime()).substring(0,7);
 	    return yueString;
	}
	
	/**
	 * 获取截止日期
	 */	
		public ActionForward getDeadline(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)throws Exception {
			   
			 JSONObject json = new JSONObject();
			 json.put("day", hqBBSetManage.getDeadline("2"));
			 response.getWriter().print(json);
			return null;
		}

	/**
	 * 设置截止日期
	 */	
			public ActionForward setDeadline(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)throws Exception {
				String deadlineString = request.getParameter("deadline");
				JSONObject json = new JSONObject();
				json.put("success", hqBBSetManage.setDeadline(deadlineString,"2"));
				response.getWriter().print(json);
				return null;
			}	
			
	/**
	 * 计算按年统计时的总数
	 */
		public Integer sumbyyear(String yearString){
			Integer countInteger=1;
			String todayString  = ToolKit.FormatDate(new Date());
			String thisyearString = todayString.substring(0,4);
			String thismonthString = todayString.substring(5,7);
			Integer thismonthInteger = (new Date()).getMonth();
			if (yearString.equals(thisyearString)){ //this year
				if(!"01".equals(thismonthString)){   //不是1月
					 if(isIntime(todayString,getMonthBefore(todayString.substring(0,7)))){  //未到截止日期
					     	countInteger = thismonthInteger -1;
					 }else{																//已到截止日期
						 	countInteger = thismonthInteger;
					 }
				}	
			}else{
				countInteger=12; //other year
			}
			return countInteger;
				
		}
	/**
	* 计算时段统计时的总数
	*/
		public Integer sumbymonth(String beginmonth, String endmonth)throws Exception{
			
			Date beginDate = ToolKit.FormatDate(beginmonth+"-01");
			Date endDate = ToolKit.FormatDate(endmonth+"-01");
			Integer beginYear = beginDate.getYear();
			Integer beginMonth = beginDate.getMonth();

			Integer endYear = endDate.getYear();
			Integer endMonth = endDate.getMonth();

			Integer difMonth = (endYear-beginYear)*12+(endMonth-beginMonth)+1;	
			return difMonth;
						
		}
}

